<template>
  <div class="comment-container">
    <div class="options">
      <h1>资源类型</h1>
      <el-select
        v-model="type"
        class="select"
        @change="GetListByType"
        placeholder="请选择资源类型"
      >
        <el-option
          v-for="item in options"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        >
        </el-option>
      </el-select>
      <h1>资源</h1>
      <el-select
        v-model="selectedId"
        class="select"
        filterable
        :disabled="!type"
        v-if="type == 'article'"
        @change="getCommentList"
        placeholder="请选择"
      >
        <el-option
          v-show="type == 'article'"
          v-for="item in selectedOptions"
          :key="item.id"
          :label="item.article_title"
          :value="item.id"
        >
        </el-option>
        <el-pagination
          small
          @current-change="pageChange"
          layout="prev, pager, next"
          :page-size="limit"
          :total="count"
        >
        </el-pagination>
      </el-select>
      <el-select
        v-model="selectedId"
        class="select"
        filterable
        :disabled="!type"
        v-if="type == 'musicScore'"
        @change="getCommentList"
        placeholder="请选择"
      >
        <el-option
          v-show="type == 'musicScore'"
          v-for="item in selectedOptions"
          :key="item.id"
          :label="item.music_score_title"
          :value="item.id"
        >
        </el-option>
        <el-pagination
          small
          @current-change="pageChange"
          layout="prev, pager, next"
          :page-size="limit"
          :total="count"
        >
        </el-pagination>
      </el-select>
      <el-select
        v-model="selectedId"
        class="select"
        filterable
        :disabled="!type"
        v-if="type == 'video'"
        @change="getCommentList"
        placeholder="请选择"
      >
        <el-option
          v-show="type == 'video'"
          v-for="item in selectedOptions"
          :key="item.id"
          :label="item.video_title"
          :value="item.id"
        >
        </el-option>
        <el-pagination
          small
          @current-change="pageChange"
          layout="prev, pager, next"
          :page-size="limit"
          :total="count"
        >
        </el-pagination>
      </el-select>
      <el-select
        v-model="selectedId"
        class="select"
        filterable
        :disabled="!type"
        v-if="type == 'document'"
        @change="getCommentList"
        placeholder="请选择"
      >
        <el-option
          v-show="type == 'document'"
          v-for="item in selectedOptions"
          :key="item.id"
          :label="item.document_title"
          :value="item.id"
        >
        </el-option>
        <el-pagination
          small
          @current-change="pageChange"
          layout="prev, pager, next"
          :page-size="limit"
          :total="count"
        >
        </el-pagination>
      </el-select>
      <el-button type="danger" v-if="selectedId" @click="CommentBatchDelete"
        >批量删除评论</el-button
      >
      <el-button
        type="danger"
        v-if="selectedId"
        @click="ReplyCommentBatchDelete"
        >批量删除回复评论</el-button
      >
      <el-button
        style="margin-left:20px"
        type="warning"
        v-if="selectedId"
        @click="OpenDeleteListDialog"
        >待删除列表</el-button
      >
    </div>
    <div class="commentList">
      <el-table
        :data="commentList"
        style="width: 100%;margin-bottom: 20px;"
        row-key="id"
        @expand-change="handleNodeExpand"
        border
        @selection-change="CommentSelectionChange"
        :default-expand-all="false"
        :tree-props="{ children: 'children' }"
      >
        <el-table-column type="selection" width="55"> </el-table-column>
        <el-table-column type="expand">
          <template
            slot-scope="props"
            style="display:flex;justify-content:center"
          >
            <el-table
              :data="props.row.children.payload"
              v-if="props.row.children.payload"
              @selection-change="ReplyCommentSelectionChange"
              style="width: 100%"
            >
              <el-table-column type="selection" width="55"> </el-table-column>
              <el-table-column prop="commenter_name" label="时间" width="100">
                <template slot-scope="scope">
                  <span>{{ scope.row.create_time | formatDate }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="commenter_name" label="评论人" width="100">
              </el-table-column>
              <el-table-column
                prop="to_commenter_name"
                label="被评论人"
                width="100"
              >
              </el-table-column>
              <el-table-column
                prop="comment_content"
                label="评论内容"
                width="100"
              >
              </el-table-column>
              <el-table-column prop="like_count" label="点赞数" width="100">
              </el-table-column>
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button
                    size="mini"
                    type="danger"
                    @click="DeleteReplyComment(scope.$index, scope.row)"
                    >删除</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
            <div v-else class="empty-container">
              <img
                src="@/assets/img/comment-empty.png"
                style="width:300px;margin:0 auto;"
              />
            </div>
            <el-pagination
              small
              :page-size="props.row.children.limit"
              @current-change="ReplyPageChange(props.row.children)"
              layout="prev, pager, next"
              :total="props.row.children.count"
            >
            </el-pagination>
          </template>
        </el-table-column>
        <el-table-column prop="create_time" label="日期" sortable width="180">
          <template slot-scope="scope">
            <span>{{ scope.row.create_time | formatDate }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="creator_name"
          label="评论人"
          sortable
          width="180"
        >
        </el-table-column>
        <el-table-column prop="comment_content" label="评论内容">
        </el-table-column>
        <el-table-column prop="like_count" label="点赞数"> </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="danger"
              @click="DeleteComment(scope.$index, scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
        <el-pagination
          small
          :page-size="limit"
          @current-change="pageChange"
          layout="prev, pager, next"
          :total="count"
        >
        </el-pagination>
      </el-table>
      <!-- 删除列表对话框 -->

      <DeleteListDialog
        :data="DeleteList"
        dialogTitle="删除评论列表"
        :pageSize="pageSize"
        :total="total"
        :commentType="type"
        type="comment"
        @custom-reload="getDeleteList"
        @current-page-change="DeleteListPageChange"
        :visible="DeleteListDialogVisible"
        @custom-close="DeleteListDialogClose"
      />
    </div>
  </div>
</template>

<script>
import DeleteListDialog from '@/components/Dialog/DeleteListDialog'

export default {
  props: {},
  components: {
    DeleteListDialog
  },
  data() {
    return {
      type: '',
      selectedId: '',
      options: [
        {
          value: 'article',
          label: '文章'
        },
        {
          value: 'musicScore',
          label: '乐谱'
        },
        {
          value: 'video',
          label: '视频'
        },
        {
          value: 'document',
          label: '文档'
        }
      ],
      selectedOptions: [],
      limit: 5,
      page: 1,
      count: 0,
      // 评论数据
      commentLimit: 10,
      commentPage: 1,
      commentCount: 0,
      commentList: [],
      defaultProps: {},
      selectedComments: '',
      selectedReplyComments: '',
      DeleteListDialogVisible: false,
      DeleteList: [], // 已删除列表
      // 删除列表分页信息
      pageSize: 3,
      currentPage: 1,
      total: null,
      currentComment: null // 当前展开的评论
    }
  },
  computed: {},
  watch: {},
  created() {},
  mounted() {},
  methods: {
    // 关闭已删除列表回调
    DeleteListDialogClose() {
      // 重新获取文章列表
      this.getCommentList().then(() => {
        this.DeleteListDialogVisible = false
      })
    },
    // 打开待删除列表
    OpenDeleteListDialog() {
      this.getDeleteList()
        .then(() => {
          this.DeleteListDialogVisible = true
        })
        .catch(error => {
          console.log(error)
          this.$message.error('获取已删除列表失败')
        })
    },
    // 获取已删除列表
    async getDeleteList() {
      const { pageSize, currentPage, type, selectedId } = this
      let res
      switch (type) {
        case 'article':
          res = await this.$API.comment.getArticleCommentDeleteList(
            selectedId,
            pageSize,
            currentPage
          )
          break
      }
      // 如果未获取到数据就退回一页重新获取数据
      if (res && !res.data) {
        if (currentPage <= 1) {
          return (this.DeleteList = [])
        } else {
          this.currentPage--
          this.getDeleteList()
        }
      }
      if (res.status == 200) {
        this.DeleteList = res.data.payload
        this.total = res.data.count
      } else {
        return this.$message.error('获取以删除列表失败')
      }
    },
    // 已删除列表页数改变
    DeleteListPageChange(currentPage) {
      this.currentPage = currentPage
      // 重新获取列表
      this.getDeleteList()
    },
    // 评论页数变化
    pageChange(page) {
      this.page = page
      this.getCommentList()
    },
    ReplyPageChange(comment, page) {
      // this.$set(comment, 'page', page)
      // this.getReplyCommentList(comment)
    },
    // 动态获取回复列表数据
    async getReplyCommentList(comment) {
      const res = await this.$API.comment.getReplyCommentList(
        comment.limit,
        comment.page
      )
      if (res.status == 200) {
        this.$set(comment, 'count', comment.count)
      }
    },
    // 通过选中的type获取列表
    async GetListByType() {
      // 重置数据
      this.page = 1
      this.selectedId = '请选择'
      this.getList()
    },
    async getList() {
      const { limit, page } = this

      let res

      switch (this.type) {
        case 'article':
          res = await this.$API.article.getArticleList(limit, page)
          break
        case 'musicScore':
          res = await this.$API.musicScore.getMusicScoreList(limit, page)

          break
        case 'video':
          res = await this.$API.video.getVideoList(limit, page)

          break
        case 'document':
          res = await this.$API.document.getDocumentList(limit, page)

          break
      }
      if (res.status == 200) {
        this.selectedOptions = res.data.payload
        this.count = res.data.count
      }
    },
    // 页数变化
    pageChange(page) {
      this.page = page
      this.getList()
    },
    // 获取评论列表
    async getCommentList() {
      this.commentList = []
      const { commentLimit, commentPage, type, selectedId } = this
      let res
      switch (type) {
        case 'article':
          res = await this.$API.comment.getCommentListByArticleId(
            selectedId,
            commentLimit,
            commentPage
          )
          break
        case 'musicScore':
          res = await this.$API.comment.getCommentListByMusicScoreId(
            selectedId,
            commentLimit,
            commentPage
          )
          break
        case 'video':
          res = await this.$API.comment.getCommentListByVideoId(
            selectedId,
            commentLimit,
            commentPage
          )
          break
        case 'document':
          res = await this.$API.comment.getCommentListByDocumentId(
            selectedId,
            commentLimit,
            commentPage
          )
          break
      }
      if (!res.data) return (this.commentList = [])
      if (res.status == 200) {
        this.commentList = res.data.payload
        this.commentCount = res.data.count
      }
    },
    // 展开回复评论列表
    async handleNodeExpand(node) {
      console.log(node)
      // 初始化数据
      this.$set(node, 'children', {})
      this.$set(node.children, 'limit', 10)
      this.$set(node.children, 'page', 1)
      const res = await this.$API.comment.getReplyCommentList(
        node.id,
        node.children.limit,
        node.children.page
      )
      console.log('reply', res)
      if (!res.data) return this.$set(node, 'children', {})
      if (res.status === 200) {
        this.$set(node, 'children', {
          count: res.data.count,
          page: node.page,
          payload: res.data.payload
        })
        this.currentComment = node
      }
    },

    DeleteReplyComment(id, replyComment) {
      this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          let formData = new FormData()
          formData.append('reply_id', replyComment.id)
          const res = await this.$API.comment.DeleteReplyComment(formData)
          if (res.status == 200) {
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
            // 初始化数据
            this.getCommentList()
          } else {
            this.$message({
              type: 'error',
              message: '删除失败!'
            })
          }
        })
        .catch(err => {
          console.log(err)
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 删除评论
    DeleteComment(id, comment) {
      const { type } = this
      this.$confirm('此操作将永久删除该评论, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          console.log(comment)
          let formData = new FormData()
          formData.append('comment_id', comment.id)
          let res
          // 根据类型删除评论
          switch (type) {
            case 'article':
              res = await this.$API.comment.DeleteArticleComment(formData)
              break
            case 'musicScore':
              console.log(formData)

              res = await this.$API.comment.DeleteMusicScoreComment(formData)
              break
            case 'video':
              res = await this.$API.comment.DeleteVideoComment(formData)
              break
            case 'document':
              res = await this.$API.comment.DeleteDocumentComment(formData)
              break
          }
          if (res.status == 200) {
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
            // 初始化数据
            this.getCommentList()
          } else {
            this.$message({
              type: 'error',
              message: '删除失败!'
            })
          }
        })
        .catch(err => {
          console.log(err)
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 多选项切换时
    CommentSelectionChange(selection) {
      this.selectedComments = selection
    },
    ReplyCommentSelectionChange(selection) {
      this.selectedReplyComments = selection
    },
    // 批量删除评论
    CommentBatchDelete() {
      if (this.selectedComments.length === 0) {
        this.$message.warning('请选择要删除的评论')
        return
      }

      this.$confirm('此操作将永久删除选中的文章, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const { type } = this
          const commentIds = this.selectedComments.map(comment => comment.id)
          const formData = new FormData()
          formData.append('comment_ids', commentIds.join(','))
          let res
          switch (type) {
            case 'article':
              res = await this.$API.comment.BatchDeleteArticleComment(formData)
              break
            case 'musicScore':
              res = await this.$API.comment.BatchDeleteMusicScoreComment(
                formData
              )
              break
            case 'video':
              res = await this.$API.comment.BatchDeleteVideoComment(formData)
              break
            case 'document':
              res = await this.$API.comment.BatchDeleteDocumentComment(formData)
              break
          }
          if (res.status === 200) {
            this.$message.success('批量删除成功')
            this.getCommentList()
            this.content = ''
            this.selectedComments = []
          } else {
            this.$message.error('批量删除失败')
          }
        })
        .catch(err => {
          console.log(err)
          this.$message.info('已取消批量删除')
        })
    },
    // 批量删除回复评论
    ReplyCommentBatchDelete() {
      if (this.selectedReplyComments.length === 0) {
        this.$message.warning('请选择要删除的回复评论')
        return
      }

      this.$confirm('此操作将永久删除选中的文章, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const { type } = this
          const replycommentIds = this.selectedReplyComments.map(
            replyComment => replyComment.id
          )
          const formData = new FormData()
          formData.append('reply_ids', replycommentIds.join(','))
          let res = this.$API.comment.BatchDeleteReplyComment(formData)

          if (res.status === 200) {
            this.$message.success('批量删除成功')
            this.selectedReplyComments = []

            this.getCommentList()
            this.content = ''
          } else {
            this.$message.error('批量删除失败')
          }
        })
        .catch(err => {
          console.log(err)
          this.$message.info('已取消批量删除')
        })
    }
  }
}
</script>

<style scoped>
.comment-container {
  width: 100%;
  padding: 20px;
}
.options {
  width: 100%;
  display: flex;
}
.options h1 {
  font-size: 15px;
  margin-right: 20px;
}
.commentList {
  margin: 20px 0;
}
.select {
  margin-right: 20px;
}
.empty-container {
  width: 100%;
  display: flex;
  justify-content: center;
}
</style>
